package dao.admin.impl;

import dao.BaseDao;
import dao.admin.BookSortDao;
import entity.Book_sort;
import entity.Books;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * BookSortDaoImpl
 *
 * @author 谭文斌
 * @since 2023/9/5
 */
public class BookSortDaoImpl extends BaseDao implements BookSortDao {
    @Override
    public List<Book_sort> getList() {
        List<Book_sort> list = new ArrayList<>();
        String sql = "select * from book_sort";
        Connection conn=getConnection();
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            ps= conn.prepareStatement(sql);
            rs=ps.executeQuery();
            while (rs.next()) {
                Book_sort book =new Book_sort();
                book.setId(rs.getInt("id"));
                book.setName(rs.getString("name"));
                book.setDescription(rs.getString("description"));
                list.add(book);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            closeAll(rs,ps,conn);
        }
        return list;
    }

    @Override
    public int add(Book_sort book) {
        String sql="insert book_sort(name,description) values (?,?)";
        return super.executeUpdate(sql,book.getName(),book.getDescription());
    }

    @Override
    public int del(int id) {
        String sql = "delete from book_sort where id=?";
        return super.executeUpdate(sql, id);
    }

    @Override
    public int upd(Book_sort book) {
        String sql = "update book_sort set name=?,description=? where id=?";
        return super.executeUpdate(sql, book.getName(), book.getDescription(),book.getId());
    }

    @Override
    public int getName(String name) {
        int row=0;
        String sql = "select count(*) c from book_sort where name=?";
        Connection conn=getConnection();
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            ps= conn.prepareStatement(sql);
            ps.setString(1, name);
            rs=ps.executeQuery();
            while (rs.next()) {
                row=rs.getInt("c");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            closeAll(rs,ps,conn);
        }
        return row;
    }

    @Override
    public int updId(int oldSort_id ) {
        String sql = "update books set sort_id=1 where sort_id=?";
        return super.executeUpdate(sql,oldSort_id);
    }
}
